package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Role;
import com.itheima.health.service.RoleService;

import com.itheima.health.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/role")
public class RoleCoontroller {
    private UserService userService;
    @Reference
    private RoleService roleService;


    @RequestMapping("/findId")
    public Result findId() {

        try {
            //从授权框架上下文对象中 获取认证对象
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            //再从 认证对象中 获取授权框架用户对象User
            User user = (User) authentication.getPrincipal();
            //用户对象User 获取 用户名
            String username = user.getUsername();
            //获取成功, 返回成功信息, 并返回用户名
            System.out.println("username = " + username);
            //根据用户名获取用户id
            Role role = roleService.findId(username);
            return new Result(true, "角色信息查询成功", role);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "角色信息查询失败");
        }
    }


    /**
     * 登录成功
     *
     * @return
     */
    @RequestMapping("/loginSuccess")
    public Result loginSuccess() {
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

    /**
     * 登录失败
     *
     * @return
     */
    @RequestMapping("/loginFail")
    public Result loginFail() {
        return new Result(false, "登录失败");
    }


    @RequestMapping("/login")
    public Result login(String username, String password) {
        System.out.println("oms backend====u:" + username + " ,p:" + password);
        if (userService.login(username, password)) {
            System.out.println("login ok!!!");
            return new Result(true, MessageConst.ACTION_SUCCESS);
        } else {
            System.out.println("login fail");
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }
}
